

(function($) {
	
	$.widget("ui.textbox", $.extend({ } ,$.ui.mouse, {
		
		options: { 
			// initial values are stored in the widget's prototype 
			required: false,
			requiredMsg: "es requerido",
			errorClass: 'error',
			validation: []
		},			
		
		_init: function() {
		
			this._setData('value', this.element.val());
			
		},
		
		getValue: function() {
			this.element.trigger('onGetValue', [this._getData('value')]);
		},
		
		disable: function() {
			this.element.attr("disabled", "disable");
		},		
		
		enable: function() {
			this.element.attr("disabled", "");
		},	
		
		refresh: function() {
			this.element.val("");
			this._setData('value', "");
		},			
		
		checkValidationList: function() {
			var errors = [];
			
			var actualValue = this._getData('value');
			
			// CHECK EACH VALIDATION REGEX
			var len = this.options.validation.length;
			for(var i=0; i<len; i++) {
				var item = this.options.validation[i];
				var regEx = item.regEx;
				var errorMsg = item.errorMsg;
				if (!regEx.test(actualValue)){
					errors.push(errorMsg);
				}
			}						
			return errors;
		},		
		
		validate: function() {
		
			var errors = [];
			this._setData('value', this.element.val());
			var actualValue = this.element.val();
			
			// CHECK IF REQUIRED
			if (this.options.required){
				if (actualValue == ""){
					if (this.options.requiredMsg !== undefined){
						errors.push(this.options.requiredMsg);
					}
				}
				else {
					// CHECK EACH VALIDATION REGEX
					errors = this.checkValidationList();					
				}
			}
			else {
				if (actualValue != ""){
					errors = this.checkValidationList();
				}
			}	
			
			
			if (errors.length > 0){
				this.element.addClass(this.options.errorClass);
			}
			else {
				if (this.element.hasClass(this.options.errorClass)){
					this.element.removeClass(this.options.errorClass);
				}
				
			}
			
			if (errors.length > 0) {
				this.element.trigger('onValidationErrors', [errors]);
			}
			
		},
		
		
		externalError: function() {

			if (!this.element.hasClass(this.options.errorClass)){
				this.element.addClass(this.options.errorClass);
			}
			
		}		
		
			
		
	}));

	
})(jQuery);


